<template>
    <!-- 居中布局 -->
    <div class="center-div">
        <div style="width: 400px; max-width: 100%;">
            <el-tabs model-value="loginByUsername" type="border-card">
                <!-- <el-tab-pane label="一键登录" name="loginByToken">
                    <el-row justify="center" align="middle" style="height: 100%;">
                        <el-button type="primary" @click="loginByToken" :loading="isLoading">点击登录</el-button>
                    </el-row>
                </el-tab-pane> -->
                <el-tab-pane label="用户名" name="loginByUsername">
                    <el-form :model="loginByUsernameForm" labelPosition="right" label-width="auto"
                             :rules="loginByUsernameFormRules" ref="loginByUsernameFormRef" status-icon>
                        <el-form-item label="用户名" :required="true" prop="username">
                            <el-input v-model="loginByUsernameForm.username" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="密码" :required="true" prop="password">
                            <el-input type="password" v-model="loginByUsernameForm.password" clearable></el-input>
                        </el-form-item>
                        <el-form-item label=" ">
                            <el-button type="primary" @click="loginByUsername" :loading="isLoading">登录</el-button>
                        </el-form-item>

                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </div>
        <!-- 多角色选择 -->
        <el-dialog title="检测到您拥有多名角色，请选择其中之一进行登录" v-model="selectRoleDialogVisible"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false" :show-close="false">
            <el-radio-group v-model="selectRoleRadio">
                <el-radio v-for="(item, index) in loginStore.availableRoles" :label="index" size="large" border>
                    {{ item }}
                </el-radio>
            </el-radio-group>
            <template #footer>
                <el-button type="primary" @click="selectRole">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {myAxios} from '../assets/ts/my-axios'
import {ref} from 'vue'
import {ElMessage, FormRules, FormInstance} from 'element-plus';
import {afterLogin, useLoginStore} from '../assets/ts/login';

// 登录中状态
const isLoading = ref(false)

// 登录上下文
// const loginContext: LoginContext = inject('loginContext', LoginContext.getInstance, true)
const loginStore = useLoginStore()
// loginStore.$subscribe(callback, {detached: true})


// =================================== 用户名登录 ======================================

// 账号密码登录表单
const loginByUsernameForm = ref({
    username: '',
    password: ''
})

// 表单验证规则
const loginByUsernameFormRules = ref<FormRules>({
    username: [
        {required: true, message: "请输入用户名", trigger: "blur"},
        {min: 4, max: 100, message: "长度限制为4-100字符", trigger: "blur"},
    ],
    password: [
        {required: true, message: "请输入密码", trigger: "blur"},
        {min: 4, max: 16, message: "长度限制为4-16字符", trigger: "blur"},
    ],
})

// 表单dom的映射
const loginByUsernameFormRef = ref<FormInstance>()

// 提交表单
function loginByUsername() {
    let formInstance = loginByUsernameFormRef.value
    if (!formInstance) return
    // TODO 开启验证
    formInstance.validate((valid, _fields) => {
        if (valid) {
            isLoading.value = true
            myAxios.post('/login/username', loginByUsernameForm.value)
                .then((response: any) => {
                    if (response.data.code == 0) {
                        loginStore.set(response.data.data)
                        // 多角色时选择一个角色
                        if (Object.keys(loginStore.roles).length > 1) {
                            selectRoleDialogVisible.value = true
                        } else {
                            afterLogin(loginStore.nickname)
                        }
                    } else {
                        ElMessage.error(response.data.message)
                    }
                }).finally(() => {
                isLoading.value = false
            })
        }
    })
}

// =================================== 选择角色 ======================================

const selectRoleDialogVisible = ref(false)
const selectRoleRadio = ref('')

// 选择角色 - 提交
function selectRole() {
    myAxios.post('/login/select-role', {roleCode: selectRoleRadio.value}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
        .then((response: any) => {
            if (response.data.code == 0) {
                loginStore.set(response.data.data)
                afterLogin(loginStore.nickname)
            } else {
                ElMessage.error(response.data.message)
            }
        }).finally(() => {
        selectRoleDialogVisible.value = false
    })
}


</script>

<style scoped></style>